const express = require('express');
const cors = require('cors'); // 引入 cors 中间件
const app = express();
app.use(cors()); // 使用 cors 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true })); // 新增这一行

const db = require('./models');

// 同步模型到数据库
(async () => {
    try {
        await db.sequelize.sync();
        console.log('Models synced successfully.');
    } catch (error) {
        console.error('Error syncing models:', error);
    }
})();

// 获取 User 模型
const User = db.User; // 修改为直接从 db 对象获取 User 模型
if (!User) {
    throw new Error('User model is not defined');
}

// 注册接口
app.post('/register', async (req, res) => {
    try {
        const { username, password, email } = req.body;

        // 验证参数是否存在
        if (!username || !password || !email) {
            return res.status(400).json({
                code: 10005,
                error: '用户名、密码和邮箱是必填项'
            });
        }

        // 校验用户名格式（字母数字下划线，3-20字符）
        const usernameRegex = /^[a-zA-Z0-9_]{3,20}$/;
        if (!usernameRegex.test(username)) {
            return res.status(400).json({
                code: 10004,
                error: '用户名格式不合法，应为3-20位字母、数字或下划线'
            });
        }

        // 校验密码格式（6-20位，包含字母和数字）
        const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/;
        if (!passwordRegex.test(password)) {
            return res.status(400).json({
                code: 10003,
                error: '密码格式不合法，应为6-20位且包含字母和数字'
            });
        }

        // 校验邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return res.status(400).json({
                code: 10006,
                error: '邮箱格式不合法'
            });
        }

        // 检查用户名或邮箱是否已存在
        const existingUser = await db.User.findOne({ where: { username } });
        if (existingUser) {
            return res.status(400).json({
                code: 10001,
                error: '用户名已存在'
            });
        }

        const existingEmail = await db.User.findOne({ where: { email } });
        if (existingEmail) {
            return res.status(400).json({
                code: 10002,
                error: '邮箱已被注册'
            });
        }

        // 创建用户，默认角色为 'user'
        const user = await db.User.create({ username, password, email, role: 'user' });
        res.status(201).json({
            code: 10000,
            message: '注册成功',
            user
        });
    } catch (error) {
        res.status(500).json({
            code: 50000,
            error: error.message
        });
    }
});

// 登录接口
app.post('/login', async (req, res) => {
    try {
        const { username, password } = req.body;

        // 验证参数是否存在
        if (!username || !password) {
            return res.status(400).json({
                code: 10005,
                error: '用户名和密码是必填项'
            });
        }

        // 校验用户名格式
        const usernameRegex = /^[a-zA-Z0-9_]{3,20}$/;
        if (!usernameRegex.test(username)) {
            return res.status(400).json({
                code: 10003,
                error: '用户名格式不合法，应为3-20位字母、数字或下划线'
            });
        }

        // 校验密码格式
        const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/;
        if (!passwordRegex.test(password)) {
            return res.status(400).json({
                code: 10004,
                error: '密码格式不合法，应为6-20位且包含字母和数字'
            });
        }

        // 查询用户是否存在
        const user = await db.User.findOne({ where: { username } });
        if (!user) {
            return res.status(401).json({
                code: 10001,
                error: '用户名不存在'
            });
        }

        // 检查密码是否匹配
        if (user.password !== password) {
            return res.status(401).json({
                code: 10002,
                error: '密码错误'
            });
        }

        res.json({
            code: 10000,
            message: '登录成功',
            user: {
                id: user.id,
                username: user.username,
                password: user.password,
                email: user.email,
                role: user.role
            }
        });
    } catch (error) {
        res.status(500).json({
            code: 50000,
            error: error.message
        });
    }
});

// 查询所有用户
app.get('/users', async (req, res) => {
    try {
        const users = await db.User.findAll();
        res.json({
            code: 10000,
            message: '查询成功',
            data: users.map(u => ({
                id: u.id,
                username: u.username,
                password: u.password,
                email: u.email,
                role: u.role,
                createdAt: u.createdAt
            }))
        });
    } catch (error) {
        res.status(500).json({
            code: 10001,
            error: error.message
        });
    }
});

// 删除用户
app.delete('/users/:id', async (req, res) => {
    try {
        const id = Number(req.params.id);
        if (isNaN(id) || !Number.isInteger(id) || id <= 0) {
            return res.status(400).json({ code: 10007, error: '用户ID不合法' });
        }
        const user = await db.User.findByPk(id);
        if (!user) {
            return res.status(404).json({ code: 10008, error: '用户未找到' });
        }
        await user.destroy();
        res.json({ code: 10000, message: '用户删除成功' });
    } catch (error) {
        res.status(500).json({ code: 50000, error: error.message });
    }
});

// 修改用户信息
app.put('/users/:id', async (req, res) => {
    try {
        const id = Number(req.params.id);
        if (isNaN(id) || !Number.isInteger(id) || id <= 0) {
            return res.status(400).json({ code: 10007, error: '用户ID不合法' });
        }
        const user = await db.User.findByPk(id);
        if (!user) {
            return res.status(404).json({ code: 10008, error: '用户未找到' });
        }
        const { username, password, email, role } = req.body;
        // 可选字段校验
        if (username && !/^[a-zA-Z0-9_]{3,20}$/.test(username)) {
            return res.status(400).json({ code: 10004, error: '用户名格式不合法，应为3-20位字母、数字或下划线' });
        }
        if (password && !/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/.test(password)) {
            return res.status(400).json({ code: 10003, error: '密码格式不合法，应为6-20位且包含字母和数字' });
        }
        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            return res.status(400).json({ code: 10006, error: '邮箱格式不合法' });
        }
        if (role && !['user', 'admin'].includes(role)) {
            return res.status(400).json({ code: 10009, error: '角色不合法，只能为 user 或 admin' });
        }
        // 检查用户名/邮箱唯一性
        if (username && username !== user.username) {
            const existUser = await db.User.findOne({ where: { username } });
            if (existUser) {
                return res.status(400).json({ code: 10001, error: '用户名已存在' });
            }
        }
        if (email && email !== user.email) {
            const existEmail = await db.User.findOne({ where: { email } });
            if (existEmail) {
                return res.status(400).json({ code: 10002, error: '邮箱已被注册' });
            }
        }
        await user.update({ username, password, email, role });
        res.json({ code: 10000, message: '用户信息更新成功', user });
    } catch (error) {
        res.status(500).json({ code: 50000, error: error.message });
    }
});

// 图书管理接口
const Book = db.Book;
if (!Book) {
    throw new Error('Book model is not defined');
}

// 将英文错误信息翻译为中文
function translateErrorMessage (msg) {
    if (!msg) return '服务器内部错误';
    if (msg.includes("Incorrect integer value")) {
        return "某个字段的值不是有效的整数类型（如 publishedYear 传入了非数字）";
    }
    // 可根据需要继续扩展更多错误翻译
    return msg;
}

// 添加图书
app.post('/books', async (req, res) => {
    try {
        let { title, author, description, publishedYear } = req.body;
        if (!title || !author) {
            return res.status(400).json({ code: 20001, error: '书名和作者为必填项' });
        }
        // 处理 publishedYear 为空字符串的情况
        if (publishedYear === '' || publishedYear === undefined) publishedYear = null;
        const book = await Book.create({ title, author, description, publishedYear });
        res.status(201).json({ code: 20000, message: '图书添加成功', data: book });
    } catch (error) {
        res.status(500).json({ code: 50000, error: translateErrorMessage(error.message) });
    }
});

// 获取所有图书
app.get('/books', async (req, res) => {
    try {
        const books = await Book.findAll();
        res.json({ code: 20000, message: '查询成功', data: books });
    } catch (error) {
        res.status(500).json({ code: 50000, error: translateErrorMessage(error.message) });
    }
});

// 根据ID获取单本图书
app.get('/books/:id', async (req, res) => {
    try {
        const id = Number(req.params.id);
        if (isNaN(id)) {
            return res.status(500).json({ code: 50000, error: translateErrorMessage('ID 不是有效数字') });
        }
        if (!Number.isInteger(id) || id <= 0) {
            return res.status(400).json({ code: 20002, error: '图书未找到' });
        }
        const book = await Book.findByPk(id);
        if (!book) {
            return res.status(404).json({ code: 20002, error: '图书未找到' });
        }
        res.json({ code: 20000, message: '查询成功', data: book });
    } catch (error) {
        res.status(500).json({ code: 50000, error: translateErrorMessage(error.message) });
    }
});

// 更新图书
app.put('/books/:id', async (req, res) => {
    try {
        const id = Number(req.params.id);
        if (isNaN(id)) {
            return res.status(500).json({ code: 50000, error: translateErrorMessage('ID 不是有效数字') });
        }
        if (!Number.isInteger(id) || id <= 0) {
            return res.status(400).json({ code: 20002, error: '图书未找到' });
        }
        let { title, author, description, publishedYear } = req.body;
        const book = await Book.findByPk(id);
        if (!book) {
            return res.status(404).json({ code: 20002, error: '图书未找到' });
        }
        if (publishedYear === '' || publishedYear === undefined) publishedYear = null;
        await book.update({ title, author, description, publishedYear });
        res.json({ code: 20000, message: '图书更新成功', data: book });
    } catch (error) {
        res.status(500).json({ code: 50000, error: translateErrorMessage(error.message) });
    }
});

// 文章管理接口
const Article = db.Article;
if (!Article) {
    throw new Error('Article model is not defined');
}

// 添加文章
app.post('/articles', async (req, res) => {
    try {
        let { title, content, author, publishedAt } = req.body;
        if (!title || !content || !author) {
            return res.status(400).json({ code: 30001, error: '标题、内容和作者为必填项' });
        }
        if (publishedAt === '' || publishedAt === undefined) publishedAt = null;
        const article = await Article.create({ title, content, author, publishedAt });
        res.status(201).json({ code: 30000, message: '文章添加成功', data: article });
    } catch (error) {
        res.status(500).json({ code: 50000, error: translateErrorMessage(error.message) });
    }
});

// 获取所有文章
app.get('/articles', async (req, res) => {
    try {
        const articles = await Article.findAll();
        res.json({ code: 30000, message: '查询成功', data: articles });
    } catch (error) {
        res.status(500).json({ code: 50000, error: translateErrorMessage(error.message) });
    }
});

// 根据ID获取单篇文章
app.get('/articles/:id', async (req, res) => {
    try {
        const id = Number(req.params.id);
        if (isNaN(id)) {
            return res.status(500).json({ code: 50000, error: translateErrorMessage('ID 不是有效数字') });
        }
        if (!Number.isInteger(id) || id <= 0) {
            return res.status(400).json({ code: 30002, error: '文章未找到' });
        }
        const article = await Article.findByPk(id);
        if (!article) {
            return res.status(404).json({ code: 30002, error: '文章未找到' });
        }
        res.json({ code: 30000, message: '查询成功', data: article });
    } catch (error) {
        res.status(500).json({ code: 50000, error: translateErrorMessage(error.message) });
    }
});

// 更新文章
app.put('/articles/:id', async (req, res) => {
    try {
        const id = Number(req.params.id);
        if (isNaN(id)) {
            return res.status(500).json({ code: 50000, error: translateErrorMessage('ID 不是有效数字') });
        }
        if (!Number.isInteger(id) || id <= 0) {
            return res.status(400).json({ code: 30002, error: '文章未找到' });
        }
        let { title, content, author, publishedAt } = req.body;
        const article = await Article.findByPk(id);
        if (!article) {
            return res.status(404).json({ code: 30002, error: '文章未找到' });
        }
        if (publishedAt === '' || publishedAt === undefined) publishedAt = null;
        await article.update({ title, content, author, publishedAt });
        res.json({ code: 30000, message: '文章更新成功', data: article });
    } catch (error) {
        res.status(500).json({ code: 50000, error: translateErrorMessage(error.message) });
    }
});

// 启动服务
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
